<?php

use Core\Myapp\Zobero;
use Core\Myapp\Model\Entity\Module;
use Core\Zend\Controller\Request\Request;
use Core\Myapp\Router\Admin;
use Core\Myapp\Router\Standard;
use Core\Myapp\Router\Rewrite;
use Illuminate\Event\Dispatcher;

class Main extends Zobero
{
    const CORE_MODULE_FOLDER = 'core';
    const COMMUNITY_MODULE_FOLDER = 'community';

	protected function init()
    {
        // Load all enable module
        $this->initModules();
        $this->initEvents();
	}
    protected function initModules()
    {
        $modules = $this->getSingleton('\Core\Myapp\Helper\Module')->getModules();
        $this->setRegistry('modules', $modules);
    }
    protected function initEvents()
    {
        $eventHelper = new \Core\Myapp\Helper\Event();
        $eventHelper->collecListeners();
    }
	public function run()
    {
        $this->getSingleton('\Core\Myapp\Helper\Log\Logger')->write('Controller intialized');
		$this->init();
        if($this->dispatch())
        {
            $this->getRegistry('router')->run();
        }
        else
        {
            // Return 404
        }
	}
    protected function dispatch()
    {
        $request = $this->getInstance('\Core\Zend\Controller\Request\Request');
        $this->setRegistry('request', $request);
        $request->setPathInfo()->setDispatched(false);
        $adminRoute = new Admin();
        if($adminRoute->match($request)) {
            $request->setDispatched(true);
            $this->setRegistry('router', $adminRoute);
            $view = $this->getInstance('Core\Myapp\View\Admin\View');
            $this->setRegistry('view', $view);
            return true;
        }
        $defaultRoute = new Standard();
        if($defaultRoute->match($request)) {
            $request->setDispatched(true);
            $this->setRegistry('router', $defaultRoute);
            return true;
        }
        $rewriteRoute = new Rewrite();
        if($rewriteRoute->match($request)) {
            $request->setDispatched(true);
            $this->setRegistry('router', $rewriteRoute);
            return true;
        }
        return false;// no route match
    }
    public function getDesignPackage()
    {
        return 'default';
    }
}